package swing;

import javax.swing.*;
import java.awt.*;

public abstract class Dialog extends JDialog{
    /**
	 * 
	 */
	private static final long serialVersionUID = 8641343094390934906L;

    private final Flag[] flags;

    public static void popup(final Component component) {
        new JFrame() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1816170570654900226L;

			@Override
            public void setVisible(boolean b) {
                getContentPane().add(component);
                super.setVisible(b);
            }
        }.setVisible(true);
    }

    public enum Flag {
        PACKED, CENTERED
    }

    public Dialog(Flag... flags){
        this.flags = flags;
    }

    @Override
    public final void setVisible(boolean b) {
        for (Flag flag : flags)
            switch (flag){
                case PACKED:
                     pack();
                    break;
                case CENTERED:
                    setLocationRelativeTo(null);
                    break;
            }

        super.setVisible(b);
    }

    public void popup(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }

    public void setComponentEnabled(boolean enabled) {
        setComponentEnabled(enabled, getContentPane());
    }

    private void setComponentEnabled(boolean enabled, Component component) {
        component.setEnabled(enabled);
        if (component instanceof Container) {
            Component[] components = ((Container) component).getComponents();
            if (components != null && components.length > 0)
                for (Component heldComponent : components)
                    setComponentEnabled(enabled, heldComponent);
        }
    }
}
